package com.h3c.nem.utils;

import com.alibaba.fastjson.JSONObject;
import com.eos.common.constant.StatusCodeEnum;
import com.eos.common.custom.BusinessException;
import com.h3c.nem.client.WxFeignClient;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.Getter;
import lombok.extern.slf4j.Slf4j;
import org.apache.http.client.utils.URLEncodedUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import org.springframework.util.CollectionUtils;
import org.springframework.util.LinkedMultiValueMap;
import org.springframework.util.MultiValueMap;
import org.springframework.util.StringUtils;

import javax.annotation.Resource;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.*;

/**
 * 企业微信工具
 *
 * @author z22968
 * @date 2022/6/15 15:19
 */
@Slf4j
@Component
public class WeChatUtils {

    @Value("${wechat.appId}")
    private String appId;

    @Value("${wechat.appSecret}")
    private String appSecret;

    @Value("${wechat.agentId}")
    private String agentId;

    @Value("${wechat.url.appid}")
    private String wechatUrlAppId;

    @Value("${care.wx.img.url}")
    private String wxImgUrl;
    // token
    private static String token;

    // 过期时间
    private static long tokenExpireTime;

    @Resource
    WxFeignClient wxFeignClient;

    @Resource
    EosUtils eosUtils;

    /**
     * 获取企业微信token
     *
     * @param
     * @return java.lang.String
     * @author z22968
     * @date 2022-06-15 17:36
     */
    private String getToken() {
        if (StringUtils.isEmpty(token) || tokenExpireTime < System.currentTimeMillis()) {
            //域账号验证
            JSONObject tokenJsonObject = wxFeignClient.getToken(appId, appSecret);
            if (!tokenJsonObject.get("errcode").toString().equals("0")) {
                throw new AppBusinessException("获取企业微信Token失败");
            }
            token = ((LinkedHashMap) tokenJsonObject.get("data")).get("token").toString();
            log.info("token:{}", token);
            // 设置过期时间1小时
            tokenExpireTime = System.currentTimeMillis() + 1 * 60 * 60 * 1000;
        }
        return token;
    }

    /**
     * 通过WxCode解析出域账号
     *
     * @param wxCode
     * @return java.lang.String
     * @author z22968
     * @date 2022-06-15 17:36
     */
    public String getDomainAccount(String wxCode) {
        JSONObject userInfoJsonObject = wxFeignClient.getUserInfo(appId, getToken(), agentId, wxCode, "WX", false, "1");
        if (!userInfoJsonObject.get("errcode").toString().equals("0")) {
            throw new AppBusinessException("获取用户域账号失败,errorMessage=" + userInfoJsonObject.get("message").toString());
        }
        Object userIdObj = ((LinkedHashMap) userInfoJsonObject.get("data")).get("userid");
        if (userIdObj == null) {
            throw new AppBusinessException("获取用户域账号失败2,errorMessage=" + userInfoJsonObject);
        } else {
            String domainAccount = (String) userIdObj;
            domainAccount = domainAccount.toLowerCase();
            log.info(domainAccount);
            return domainAccount;
        }
    }

    /**
     * 发送企业微信图文消息
     *
     * @param sendTo      域账号String, 逗号分隔
     * @param title       标题
     * @param description 描述
     * @param url         点击跳转地址
     * @param picUrl      图片地址
     * @return void
     * @author z22968
     * @date 2022-06-20 10:48
     */
    public void sendWeChatImageMsg(String sendTo, String title, String description, String url) {
        if (StringUtils.isEmpty(sendTo)) {
            throw new AppBusinessException("接收人不能为空");
        }
        String[] adAccountList = sendTo.split(",");
        if (adAccountList.length == 0) {
            throw new AppBusinessException("接收人不能为空");
        }
        List<String> accountList = CollectionUtils.arrayToList(adAccountList);
        eosUtils.sendEosWeChatImageMsg(accountList, agentId, title, description, url, wxImgUrl);
    }

    public String getWeChatOpenUrl(String redirectUrl) throws UnsupportedEncodingException {
        String wxOpenUrl = String.format("https://open.weixin.qq.com/connect/oauth2/authorize?appid=%s&redirect_uri=%s&response_type=code&scope=snsapi_base#wechat_redirect"
                , wechatUrlAppId, URLEncoder.encode(redirectUrl, "UTF-8"));
        return wxOpenUrl;
    }
}
